/*
 * @Description: 规范性检测上下文
 * @Author: Rfan
 * @Date: 2022-11-19 16:31:39
 * @LastEditTime: 2022-12-08 15:30:51
 */

import { createContext, useContext, useEffect, useReducer } from 'react';
import {
  DELETE_REGISTRATION_ITEM,
  SET_SELECTED_ITEM,
  ADD_REG_DESTRUCTION,
  EDIT_REG_DESTRUCTION,
  SET_REG_DESTRUCTION_LIST
} from '../constants';
import { DestructionReducer } from '../reducers/DestructionReducer';
import { message, Modal } from 'antd';
import {
  addRegDestruction,
  deleteRegDestructionItem,
  editRegDestruction,
  fetchRegDestructionListByPage
} from '@/api/registration/destruction';

const initialState = {
  // 当前选中的项目
  selectFond: {},
  selectAT: {},
  selectFondId: 0,
  selectATId: 0,
  // 选中的表格条目
  selectItems: [],

  list: []

  // -------- 字典 --------
};

const DestructionContext = createContext();

const DestructionProvider = (props) => {
  const [state, dispatch] = useReducer(DestructionReducer, initialState);

  const actions = {
    /**
     * @description: 设置表格中选中条目的key
     * @param {*} selectArr
     * @return {*}
     */
    setSelectKey(selectArr) {
      dispatch({ type: SET_SELECTED_ITEM, data: selectArr });
    },

    /**
     * @description: 获取电子档案销毁登记列表
     * @param {IPageQuery<IRegDestructionListParams>} query
     * @return {*}
     */
    getRegDestructionList(query) {
      return new Promise((resolve, reject) => {
        fetchRegDestructionListByPage(query)
          .then((res) => {
            const { data } = res;
            console.log('pending', data);
            dispatch({
              type: SET_REG_DESTRUCTION_LIST,
              data: data.results
            });
            resolve(data);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },

    /**
     * @description: 增加电子档案销毁登记
     * @param {IAddRegDestructionParams} params
     * @return {any}
     */
    addRegDestructionFunc(params) {
      return new Promise((resolve, reject) => {
        addRegDestruction(params)
          .then((res) => {
            const { data } = res;
            dispatch({ type: ADD_REG_DESTRUCTION, data, id: data.id });
            resolve(data);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },

    /**
     * @description: 编辑电子档案销毁登记
     * @param {IEditRegDestructionParams} params
     * @return {any}
     */
    editRegDestructionFunc(params) {
      return new Promise((resolve, reject) => {
        editRegDestruction(params)
          .then((res) => {
            const { data } = res;
            dispatch({ type: EDIT_REG_DESTRUCTION, data, id: data.id });
            resolve(data);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },

    /**
     * @description: 删除登记条目
     * @param {number|number[]} id
     * @param {string} title
     */
    deleteItem(id, title = '是否移除选中的条目?') {
      Modal.confirm({
        title: '删除',
        content: title,
        onOk() {
          const ids = id instanceof Array ? id.join(',') : id;
          deleteRegDestructionItem(ids).then((res) => {
            const data = res.data.map((id) => parseInt(id, 10));
            message.success('删除成功');
            dispatch({ type: DELETE_REGISTRATION_ITEM, ids: data });
          });
        },
        onCancel() {
          console.log('del item Cancel');
        }
      });
    }
  };

  const filters = {
    sourcesFilter(id) {
      return state.sourcesList.find((item) => item.id === id)?.name || '-';
    },
    stateFilter(id) {
      return state.stateList.find((item) => item.id === id)?.name || '-';
    }
  };

  useEffect(() => {}, []);

  return (
    <DestructionContext.Provider value={{ ...state, ...actions, ...filters }}>
      {props.children}
    </DestructionContext.Provider>
  );
};

export const useDestructionContext = () => {
  return useContext(DestructionContext);
};

export { DestructionContext, DestructionProvider };
